package Com.Hupochuan.Uil.Util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import Com.Tester.Tester;

public class DoResponse extends HttpServletResponseWrapper{
	/*
	 * 私有类继承PrintWriter
	 */
	private static class MyPrintWriter extends PrintWriter {
		ByteArrayOutputStream myOutput;   //此即为存放response输入流的对象
		public MyPrintWriter(ByteArrayOutputStream output) {
			super(output);
			myOutput = output;
		}
		public ByteArrayOutputStream getByteArrayOutputStream() {
			return myOutput;
		}
	}
	
	private MyPrintWriter myPrintWriter;
	private ByteArrayOutputStream output;
	
	/*
	 * 构造方法
	 */
	public DoResponse(HttpServletResponse httpServletResponse) {
		super(httpServletResponse);
		this.output = new ByteArrayOutputStream();
		this.myPrintWriter = new MyPrintWriter(this.output);
	}
	
	/*
	 * 覆盖父类getWriter()方法,使用我们自己的PrintWriter
	 */
	public PrintWriter getWriter() throws IOException {
		return this.myPrintWriter;
	}
	
	/*
	 * 获得内容
	 */
	public String getContent() {
		//刷新该流的缓冲
		this.myPrintWriter.flush();
		return this.myPrintWriter.getByteArrayOutputStream().toString();
	}
	
	/*
	 * 向客户端发送数据
	 
	public void sendData(){
		PrintWriter out;
		try {
			out = super.getWriter();
			out.print(this.getContent());
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}*/
	
	/*
	 * 垃圾回收机制自动调用
	 */
	public void finalize() throws Throwable {
		super.finalize();
		Tester.print("已回收一个DoResponse");
		output.close();
		myPrintWriter.close();
	}
}
